<?php
namespace Activity\Controllers;

use Commons\Enum\StatusCode;
use Commons\Jwt;
use Phalcon\Mvc\Controller;

class BaseController extends Controller
{
    private $simpleView;
    /**
     * @var array
     */
    protected $user = null;

    public function initialize()
    {
        $this->user = $this->getUserFromJwt();
        if ($this->user === false) {
            $ctr = $this->dispatcher->getControllerName();
            $act = $this->dispatcher->getActionName();;
            if (($ctr == 'index' && $act == 'index') || ($ctr == 'index' && $act == 'gets')) {
                return;
            }
            if ($this->request->isAjax() || $this->request->isPost()) {
                $this->json([
                    'code' => 401,
                    'msg'  => '您尚未登录！'
                ], 401);
                exit();
            }
        }
    }

    /**
     * 校验jwt
     * @return bool|mixed|object
     */
    public function getUserFromJwt()
    {
        if (!empty($this->request->getHeader('jwt'))) {
            try {
                $jwt = (new Jwt())->decode($_SERVER['HTTP_JWT']);
                //                if(!isset($jwt->role_id)) {
                //                    return false;
                //                }
                //                if(isset($jwt->iat) && $jwt->iat > time()) {
                //                    return false;
                //                }
                //                if(isset($jwt->expires_in) && strtotime(($jwt->iat) + ($jwt->expires_in)) < time()) {
                //                    return false;
                //                }
                return $jwt;
            } catch (\Exception $ex) {
                return false;
            }
        }
        return false;
    }

    /**
     * json数据输出
     * 如果data是array那么需要json_encode,如果字符串直接输出
     * $unescaped 是否非转义如果选择false,输出中文等多字节字符unicode;true,不编码
     *
     * @param int          $code      响应状态码
     * @param array|string $data      需要发送的数据
     * @param bool         $unescaped 是否非转义 true非转义;false转义
     * @param bool         $numericCheck
     */
    public function json($data, $code = 200, $unescaped = true, $numericCheck = true)
    {
        $this->view->disable();
        header(StatusCode::getCode($code));
        header('Expires: 0');
        header('Cache-Control: no-cache, must-revalidate, post-check=0, pre-check=0');
        header('Pragma: no-cache');
        header('Content-type: application/json;charset=utf-8');
        if (is_array($data)) {
            if ($unescaped) {
                echo $numericCheck ? json_encode($data, JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK) : json_encode($data, JSON_UNESCAPED_UNICODE);
            } else {
                echo $numericCheck ? json_encode($data, JSON_NUMERIC_CHECK) : json_encode($data);
            }
        } else {
            echo $data;
        }
        return;
    }

    /**
     * 返回Phalcon\Mvc\View\Simple对象
     *
     * @return \Phalcon\Mvc\View\Simple
     */
    public function simpleView()
    {
        if (!is_object($this->simpleView)) {
            $this->simpleView = $this->getDI()->getShared('simple_view');
        }
        return $this->simpleView;
    }

    /**
     * 显示模板
     *
     * @param string $path
     * @param array  $params
     *
     * @return void
     */
    public function display($path = null, $params = null)
    {
        //Phalcon\Mvc\View
        $params = array_merge([], (array)$this->view->getParamsToView(), (array)$params);
        $this->view->setVars($params);
        if ($path != null && $path != '') {
            $content = $this->simpleView()->render(trim($path, '/'), $params);
            $layout  = $this->view->getLayout();
            if ($layout == '') {
                echo $content;
                exit();
            } else {
                $this->view->setContent($content);
            }
        }
        $this->view->render($this->dispatcher->getControllerName(), $this->dispatcher->getActionName(), $this->view->getParams());
    }
}
